import { useSearchParams } from "react-router-dom";
import { getQuestionListService } from "../services/question";
import { useRequest } from "ahooks";
import {
  LIST_PAGE_PARAM_KEY,
  LIST_PAGESIZE,
  LIST_PAGESIZE_PARAM_KEY,
  LIST_SEARCH_PARAM_KEY,
} from "../constant";

type OptionType = {
  isStar: boolean;
  isDeleted: boolean;
  pageSize: number;
  page: number;
};

const useLoadQuestionList = (opts?: Partial<OptionType>) => {
  const [searchParams] = useSearchParams();
  const { isStar, isDeleted } = opts || {};

  const { loading, data, error, refresh } = useRequest(
    async () => {
      const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || undefined;
      const page = parseInt(searchParams.get(LIST_PAGE_PARAM_KEY) || "1");
      const pageSize = parseInt(
        searchParams.get(LIST_PAGESIZE_PARAM_KEY) || `${LIST_PAGESIZE}`
      );
      const data = await getQuestionListService({
        keyword,
        isStar,
        isDeleted,
        page,
        pageSize,
      });
      return data;
    },
    {
      refreshDeps: [searchParams], // 刷新的依赖项
    }
  );

  return { loading, data, error, refresh };
};

export default useLoadQuestionList;
